﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace GrainManage.Data.Util
{
    public sealed class ObjectCreator
    {
        public TClass CreateInstance<TClass>() where TClass : class, new()
        {
            return Activator.CreateInstance<TClass>();
        }

        public TClass CreateInstance<TClass>(object[] constructParameters) where TClass : class
        {
            return Activator.CreateInstance(typeof(TClass), constructParameters) as TClass;
        }

        public TClass CreateInstance<TClass>(string assemblyName, string className, params object[] constructParameters) where TClass : class
        {
            Assembly assembly = null;
            if (assemblyName.ToLower().Trim().EndsWith(".dll", true, null))
            {
                assembly = Assembly.LoadFrom(assemblyName);
                assemblyName = assembly.GetName().Name;
            }
            else
            {
                assembly = Assembly.Load(assemblyName);
            }
            if (!className.StartsWith(assemblyName))
            {
                className = assemblyName + "." + className;
            }
            Type t = assembly.GetType(className);
            TClass obj = Activator.CreateInstance(t, constructParameters) as TClass;
            return obj;
        }
    }
}
